import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:qunaimedical/components/custom_divider.dart';
import 'package:qunaimedical/components/item_timely_consultation.dart';
import 'package:qunaimedical/models/consultation.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/timely_consultation_add.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/constants.dart';
import 'package:qunaimedical/values/urls.dart';

/// 即时咨询列表
class TimelyConsultationListPage extends StatefulWidget {
  const TimelyConsultationListPage({Key key}) : super(key: key);

  @override
  _TimelyConsultationListPageState createState() =>
      _TimelyConsultationListPageState();
}

class _TimelyConsultationListPageState
    extends State<TimelyConsultationListPage> {
  List<Consultation> _items = [];

  // 是否有下一页
  int _nextPage = 1;

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('即时咨询'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (c) => TimelyConsultationAddPage(),
                ),
              ).then((value) {
                if (value != null && value) {
                  _fetchData();
                }
              });
            },
            child: Text(
              '创建咨询',
              style: TextStyle(color: Theme.of(context).primaryColor),
            ),
          )
        ],
      ),
      body: SmartRefresher(
        controller: _refreshController,
        enablePullDown: true,
        enablePullUp: _nextPage != 1,
        onRefresh: _fetchData,
        onLoading: _loadMore,
        child: ListView.separated(
            padding: EdgeInsets.symmetric(vertical: 10),
            itemBuilder: (c, i) => ItemTimelyConsultation(item: _items[i]),
            separatorBuilder: (c, i) => CustomDivider(),
            itemCount: _items.length),
      ),
    );
  }

  void _fetchData() async {
    var params = {
      "pageNo": 1,
      "pageSize": Constants.limit,
      "appType": "doctor",
    };
    var result = await XHttp.postJson(Urls.TIMELY_CONSULTATION_LIST, params);
    _refreshController.refreshCompleted();
    if (result != null) {
      var response = MapResponse.fromJson(result);
      if (response.code == 1) {
        if (response.data['pages'] == response.data['current']) {
          _nextPage = 1;
        } else {
          _nextPage = response.data['pages'] + 1;
        }
        var records = (response.data['records'] as List)
            .map((e) => Consultation.fromJson((e as Map<String, dynamic>)))
            .toList();
        if (mounted) {
          setState(() {
            _items = records;
          });
        }
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  void _loadMore() async {
    var params = {
      "pageNo": _nextPage,
      "pageSize": Constants.limit,
      "appType": "doctor",
      "doctorId": SPUtils.getUser().id
    };
    var result = await XHttp.postJson(Urls.TIMELY_CONSULTATION_LIST, params);
    _refreshController.loadComplete();
    if (result != null) {
      var response = MapResponse.fromJson(result);
      if (response.code == 1) {
        if (response.data['pages'] == response.data['current']) {
          _nextPage = 1;
        } else {
          _nextPage = response.data['pages'] + 1;
        }
        var records = (response.data['records'] as List)
            .map((e) => Consultation.fromJson((e as Map<String, dynamic>)))
            .toList();
        if (mounted) {
          setState(() {
            _items.addAll(records);
          });
        }
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }
}
